package com.aerozhonghuan.logisticsmall.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aerozhonghuan.logisticsmall.R;
import com.aerozhonghuan.logisticsmall.framework.base.URLs;

import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * Created by ChenLin on 2019/5/20 15:34.Email&WeChat:7877409@163.com
 */
public class CommunityTool {

    private static CommunityTool communityTool;

    public static CommunityTool getInstance() {
        if (communityTool == null) {
            communityTool = new CommunityTool();
        }
        return communityTool;
    }

    /**
     * which 0表示返回宽  1表示返回高
     */
    public int getScreenWH(Activity activity, int which) {
        DisplayMetrics metric = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;     // 屏幕宽度（像素）
        int height = metric.heightPixels;   // 屏幕高度（像素）
        float density = metric.density;      // 屏幕密度（0.75 / 1.0 / 1.5）
        int densityDpi = metric.densityDpi;  // 屏幕密度DPI（120 / 160 / 240）
        if (which == 0) {
            return width;
        } else {
            return height;
        }
    }


    public static String changeOthersImageId(int id, int imgSize, String type) {
        String strBaseImagePath = "";
        if (type.equals("skin")) {
            strBaseImagePath = "http://mall-dev.dev188.cn/fs/";
        } else if (type.equals("triangle")) {
            strBaseImagePath = "http://mall-dev.dev188.cn/fs/";
        }
        String imageIdLength = String.valueOf(id);
        int size = 8 - imageIdLength.length();
        if (imageIdLength.length() < 8) {
            for (int i = 0; i < size; i++) {
                imageIdLength = "0" + imageIdLength;
            }
            System.out.println("补0:" + imageIdLength);
        }
        String strImageId = new StringBuffer(imageIdLength).reverse()
                .toString();
        System.out.println("反转:" + strImageId);
        int idLen = strImageId.length();
        // String strImagePath = strImageId.substring(0,
        // idLen-6)+"/"+strImageId.substring(idLen-6,3)+"/"+strImageId.substring(idLen-3);
        String strImagePath = strImageId.substring(0, idLen - 6) + "/"
                + strImageId.substring(idLen - 6, 5) + "/"
                + strImageId.substring(idLen - 3);
        return strBaseImagePath + strImagePath + "/" + id + "_" + imgSize + ".png";
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static float dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return dpValue * scale + 0.5f;
    }

    //补位，如果不足num位，则前面添加0
    public String addPosition(String str, int num) {
        if (str.length() < num) {
            while (true) {
                str = "0" + str;
                if (str.length() == num) {
                    break;
                }
            }
        }
        return str;
    }

    public Dialog createLoadingDialog(Activity context, String msg) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.progressbar_layout, null);
        LinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view);
        ImageView spaceshipImage = (ImageView) v.findViewById(R.id.img);
        TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);
        Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(
                context, R.anim.loading_animation);
        spaceshipImage.startAnimation(hyperspaceJumpAnimation);
        tipTextView.setText(msg);
        Dialog loadingDialog = new Dialog(context, R.style.loading_dialog);
        loadingDialog.setCancelable(true);
        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));

        return loadingDialog;
    }

    //将对象保存为字符串
    public static String saveObject(Object object) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            // 创建对象输出流，并封装字节流
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            // 将对象写入字节流
            oos.writeObject(object);
            // 将字节流编码成base64的字符窜
            String oAuth_Base64 = new String(Base64.encodeBase64(baos
                    .toByteArray()));
            return oAuth_Base64;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public String getYesterdayTime(String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        String date = sdf.format(calendar.getTime());
        return date;
    }

    public static Object readObject(String res) {
        Object oAuth_1 = null;
        // 读取字节
        if (!TextUtils.isEmpty(res)) {
            byte[] base64 = Base64.decodeBase64(res.getBytes());
            // 封装到字节流
            ByteArrayInputStream bais = new ByteArrayInputStream(base64);
            try {
                // 再次封装
                ObjectInputStream bis = new ObjectInputStream(bais);
                try {
                    // 读取对象
                    oAuth_1 = (Object) bis.readObject();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } catch (StreamCorruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return oAuth_1;
        }
        return null;
    }

    public static String changeImageId(int id, boolean smallpic, boolean isChat) {
        String strBaseImagePath = null;
        if (isChat) {
            strBaseImagePath = "http://mall-dev.dev188.cn/fs/";
        } else {
            strBaseImagePath = "http://mall-dev.dev188.cn/fs/";
        }
        String imageIdLength = String.valueOf(id);
        int size = 8 - imageIdLength.length();
        if (imageIdLength.length() < 8) {
            for (int i = 0; i < size; i++) {
                imageIdLength = "0" + imageIdLength;
            }
            System.out.println("补0:" + imageIdLength);
        }
        String strImageId = new StringBuffer(imageIdLength).reverse()
                .toString();
        System.out.println("反转:" + strImageId);
        int idLen = strImageId.length();
        String strImagePath = strImageId.substring(0, idLen - 6) + "/"
                + strImageId.substring(idLen - 6, 5) + "/"
                + strImageId.substring(idLen - 3);
        if (TextUtils.isEmpty(URLs.IMG.PRODUCT_IMG_SUFFIX)) {
            URLs.IMG.PRODUCT_IMG_SUFFIX = "jpg";
        }
        if (smallpic) {
            if (isChat) {
                return strBaseImagePath + strImagePath + "/" + id + "_300" + ".png";
            }
            return strBaseImagePath + strImagePath + "/" + id + "_160." + URLs.IMG.PRODUCT_IMG_SUFFIX;
        } else {
            if (isChat) {
                return strBaseImagePath + strImagePath + "/" + id + "_original.png";
            }
            return strBaseImagePath + strImagePath + "/" + id + "_300." + URLs.IMG.PRODUCT_IMG_SUFFIX;
        }
    }

    public static String changeBannerImgId(String imgBaseUrl, int imgId, String imgSize) {
        String imageIdLength = String.valueOf(imgId);
        int size = 8 - imageIdLength.length();
        if (imageIdLength.length() < 8) {
            for (int i = 0; i < size; i++) {
                imageIdLength = "0" + imageIdLength;
            }
            System.out.println("补0:" + imageIdLength);
        }
        String strImageId = new StringBuffer(imageIdLength).reverse()
                .toString();
        System.out.println("反转:" + strImageId);
        int idLen = strImageId.length();
        String strImagePath = strImageId.substring(0, idLen - 6) + "/"
                + strImageId.substring(idLen - 6, 5) + "/"
                + strImageId.substring(idLen - 3);
        if (!TextUtils.isEmpty(imgSize)) {
            return "http://mall-dev.dev188.cn/fs/" + strImagePath + "/" + imgId + "_" + imgSize + ".png";
        }
        return "http://mall-dev.dev188.cn/fs/" + strImagePath + "/" + imgId + ".png";
    }

    public static String changeImgId(String imgBaseUrl, int imgId, boolean isSmall) {
        String imageIdLength = String.valueOf(imgId);
        int size = 8 - imageIdLength.length();
        if (imageIdLength.length() < 8) {
            for (int i = 0; i < size; i++) {
                imageIdLength = "0" + imageIdLength;
            }
            System.out.println("补0:" + imageIdLength);
        }
        String strImageId = new StringBuffer(imageIdLength).reverse()
                .toString();
        System.out.println("反转:" + strImageId);
        int idLen = strImageId.length();
        String strImagePath = strImageId.substring(0, idLen - 6) + "/"
                + strImageId.substring(idLen - 6, 5) + "/"
                + strImageId.substring(idLen - 3);
        if (isSmall) {
            return imgBaseUrl + strImagePath + "/" + imgId + "_160" + ".png";
        } else {
            return imgBaseUrl + strImagePath + "/" + imgId + "_300.png";
        }
    }
}
